#pragma once

#include <iostream>
#include <cassert>
using namespace std;

namespace ephemerals
{
	template<class T>
	struct ListNode
	{
		T _data;
		ListNode<T>* _prev;
		ListNode<T>* _next;

		ListNode(const T& x = T())
			:_data(x)
			, _prev(nullptr)
			, _next(nullptr)
		{}
	};

	template<class T, class Ref, class Ptr>
	struct list_iterator
	{
		typedef ListNode<T> Node;
		typedef list_iterator<T, Ref, Ptr> Self;

		Node* _ptr;

		list_iterator(Node* node)
			:_ptr(node)
		{}

		Ref operator*()
		{
			return _ptr->_data;
		}

		Ref operator->()
		{
			return &(_ptr->_data);
		}

		Self& operator++()
		{
			_ptr = _ptr->_next;
			return *this;
		}

		Self& operator--()
		{
			_ptr = _ptr->_prev;
			return *this;
		}

		Self operator++(int)
		{
			Self tmp = *this;
			_ptr = _ptr->_next;
			return tmp;
		}

		Self operator--(int)
		{
			Self tmp = *this;
			_ptr = _ptr->_prev;
			return tmp;
		}

		bool operator!=(const Self& iterator)
		{
			return _ptr != iterator._ptr;
		}
	};

	template<class T>
	class list
	{
		typedef ListNode<T> Node;
	public:
		typedef list_iterator<T, T&, T*> iterator;
		typedef list_iterator<T, const T&, const T*> const_iterator;

		iterator begin()
		{
			return iterator(_head->_next);
		}
		iterator end()
		{
			return iterator(_head);
		}
		const_iterator begin() const
		{
			return iterator(_head->_next);
		}
		const_iterator end() const
		{
			return iterator(_head);
		}

		void empty_init()
		{
			_head = new Node();
			_head->_next = _head->_prev = _head;
			_size = 0;
		}

		list()
		{
			empty_init();
		}

		list(size_t n, const T& val = T())
		{
			empty_init();
			for (int i = 0; i < n; i++)
			{
				push_back(val);
			}
		}

		list(const list<T>& l)
		{
			empty_init();
			for (auto& e : l)
			{
				push_back(e);
			}
		}

		list<T>& operator=(list<T> l)
		{
			swap(l);
			return *this;
		}

		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}

		iterator insert(iterator pos, const T& x)
		{
			Node* cur = pos._ptr;
			Node* newnode = new Node(x);
			newnode->_next = cur;
			newnode->_prev = cur->_prev;
			cur->_prev->_next = newnode;
			cur->_prev = newnode;
			_size++;
			return iterator(newnode);
		}
		void push_back(const T& x)
		{
			insert(end(), x);
		}
		void push_front(const T& x)
		{
			insert(begin(), x);
		}

		iterator erase(iterator pos)
		{
			Node* cur = pos._ptr;
			Node* next = cur->_next;
			Node* prev = cur->_prev;
			next->_prev = prev;
			prev->_next = next;
			delete cur;
			_size--;
			return iterator(next);
		}
		void pop_back()
		{
			erase(--end());
		}
		void pop_front()
		{
			erase(begin());
		}

		void swap(list<T> l)
		{
			std::swap(_head, l._head);
			std::swap(_size, l._size);
		}

		void clear()
		{
			auto it = begin();
			while (it != end())
			{
				it = erase(it);
			}
		}
	private:
		Node* _head;
		size_t _size;
	};
}
